package dryven.view.engine.parser;

import java.io.IOException;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;

import dryven.codegen.asm.ClassBuilder;
import dryven.reflection.TypeRef;
import dryven.view.ViewDataDictionary;
import dryven.view.ViewPage;
import dryven.view.engine.expression.ViewDataDeclaration;
import dryven.view.engine.expression.nodelisters.ExpressionNodeFactory;
import dryven.view.engine.parser.parts.CompiledViewPart;

public class CompiledViewFile extends ViewPage implements ViewDataDeclarationCollection {
	private Iterable<CompiledViewPart> _parts;
	private List<ViewDataDeclaration> _declarations = new LinkedList<ViewDataDeclaration>();
	private ExpressionNodeFactory _expressionFactory;
	private ViewComponentLocator _locator;
	
	public CompiledViewFile(Iterable<CompiledViewPart> parts,
			ExpressionNodeFactory expressionFactory, ViewComponentLocator locator) {
		super();
		_parts = parts;
		_expressionFactory = expressionFactory;
		_locator = locator;
	}

	public void compile() throws CompilationException {
		for (CompiledViewPart part : _parts) {
			part.compile(this,_locator);
		}
	}
	
	public void render(ViewDataDictionary viewData, Writer out) throws IOException {
		for (CompiledViewPart part : _parts) {
			part.evaluate(viewData, out, this);
		}
	}
	
	public void buildClass(ClassBuilder builder) {
		
	}

	@Override
	public void addViewDataDeclaration(String name, String type) {
		TypeRef typeRef = _expressionFactory.convertType(type);
		ViewDataDeclaration decl = new ViewDataDeclaration(typeRef, name, _expressionFactory.create(typeRef));
		_declarations.add(decl);
	}

	@Override
	public Iterable<ViewDataDeclaration> getViewDataDeclarations() {
		return _declarations;
	}
}
